package cn.hxzy.service.impl;

import cn.hxzy.common.R;
import cn.hxzy.entity.Train;
import cn.hxzy.mapper.TrainMapper;
import cn.hxzy.service.TrainService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class TrainServiceImpl extends ServiceImpl<TrainMapper, Train> implements TrainService {

    @Autowired
    private TrainMapper trainMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R getTrain() {
        List<Train> trains = redisTemplate.opsForList().range("trains", 0, -1);
        if (trains.size()<1){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("status",1);
            List<Train> list = trainMapper.selectList(queryWrapper);
            for (Train train:list){
                redisTemplate.opsForList().leftPush("trains",train);
                redisTemplate.opsForValue().set(train.getTrainId().toString(),train);
            }
            trains = redisTemplate.opsForList().range("trains", 0, -1);
        }
        return R.ok().code(1).data("item",trains);
    }

    @Override
    public R getTrain(String startStation,String endStation) {
        List<Train> trains = redisTemplate.opsForList().range("trains", 0, -1);
        List<Train> trainterm = new ArrayList<>();
        for (Train train:trains){
            if (train.getStartStation().contains(startStation)&&train.getEndStation().contains(endStation)){
                trainterm.add(train);
            }
        }
        return R.ok().code(2).data("item",trainterm);
    }
}
